﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Threading.Tasks;
using System.Web;
using AutoMapper;
using DTcms.Core.Common.Helper;
using DTcms.Core.IServices;
using DTcms.Core.Model.Models;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;

namespace DTcms.Core.API.Controllers
{
    /// <summary>
    /// 用户下载数据
    /// </summary>
    [Route("[controller]")]
    [ApiController]
    public class DownloadController : ControllerBase
    {
        private readonly IWebHostEnvironment _hostEnvironment;
        private readonly IArticleAttachService _attachService;
        private readonly IArticleService _articleService;
        private readonly IUserService _userService;
        private readonly IMapper _mapper;

        public DownloadController(
            IArticleService articlesService,
            IUserService userService,
            IArticleAttachService attachService,
            IMapper mapper,
            IWebHostEnvironment hostEnvironment)
        {
            _articleService = articlesService;
            _userService = userService;
            _mapper = mapper;
            _attachService = attachService;
            _hostEnvironment = hostEnvironment;
        }

        [HttpGet("/client/download/{id}")]
        [Authorize]
        public async Task<IActionResult> Download([FromRoute] long id)
        {
            //获得下载ID
            if (id == 0)
            {
                return BadRequest(ResponseMessage.Error("出错了，文件参数传值不正确！"));
            }
            //获取登录用户
            var userModel = await _userService.GetUserAsync();
            if (userModel == null)
            {
                return NotFound(ResponseMessage.Error("用户尚未登录"));
            }

            ArticleAttach attachModel = await _attachService.QueryAsync<ArticleAttach>(t => t.Id == id);
            if (attachModel == null)
            {
                return BadRequest(ResponseMessage.Error("出错了，您要下载的文件不存在或已经被删除！"));
            }
            attachModel.DownCount = attachModel.DownCount + 1;
            //检查文件本地还是远程
            if (attachModel.FilePath.ToLower().StartsWith("http://") || attachModel.FilePath.ToLower().StartsWith("https://"))
            {
                var request = System.Net.HttpWebRequest.Create(attachModel.FilePath) as System.Net.HttpWebRequest;
                using (var response = request.GetResponse() as System.Net.HttpWebResponse)
                {
                    if (response.StatusCode != System.Net.HttpStatusCode.OK)
                    {
                        return BadRequest(ResponseMessage.Error("出错了，您要下载的文件不存在或已经被删除！"));
                    }
                    byte[] byteData = FileHelper.ConvertStreamToByteBuffer(response.GetResponseStream());
                    //更新下载数量
                    await _attachService.UpdateDownCount(id, userModel);
                    return File(byteData, "application/octet-stream", attachModel.FileName);
                }
            }
            else
            {
                string webRootPath = _hostEnvironment.WebRootPath;
                //获取物理路径
                string fullFileName = webRootPath + attachModel.FilePath.Replace("/", @"\");
                //检测文件是否存在
                if (!System.IO.File.Exists(fullFileName))
                {
                    return BadRequest(ResponseMessage.Error("出错了，您要下载的文件不存在或已经被删除！"));
                }
                //更新下载数量
                await _attachService.UpdateDownCount(id, userModel);
                return File(attachModel.FilePath, "application/octet-stream", attachModel.FileName);
            }
        }
    }
}
